package com.ykt.mall.ctrl;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.token.TokenManager;
import com.ykt.interceptor.Seach;
import com.ykt.mall.content.Content;
import com.ykt.mall.kit.Tools;
import com.ykt.model.Customer;
import com.ykt.model.CustomerAddress;
import com.ykt.model.Postage;
import com.ykt.model.Product;
import com.ykt.model.ProductType;
import com.ykt.model.Shop;
import com.ykt.model.ShopType;
import com.ykt.model.TempCart;

/**
 * 控制使用客户端代客下单
 * @author wing
 *
 */
@ControllerBind(controllerKey = "/app")
public class AppCtrl extends Controller{
	
	private static Logger log = Logger.getLogger(AppCtrl.class);
	protected static String tokenName="token";
	protected int tokenTout=600;
	
	/*
	 * 前往指定商户的菜单页
	 */
	//@ClearInterceptor(ClearLayer.ALL)
	@Before(Seach.class)
	public void index(){
		
		String mobileNo = getPara("mobileNo");
		String imei = getPara("imei");
		
		Integer shopId= getParaToInt("id");
		if(shopId==null) shopId=1;
		
		Shop shop = Shop.dao.findById(shopId);
		
		setAttr("shopPo", shop);
		if(getSessionAttr(Content.SESSION_SHOP) == null){
			setSessionAttr(Content.SESSION_SHOP, shop);
		}
		setAttr("mobileNo",mobileNo);
		
		////////////////////////////////////////////////
		if(shopId == 5){
			
			List<ShopType> shopTypeList = ShopType.dao.find("select * from shop_type where shop_id= ? order by seq ;",shopId);
			Map<Integer,List<Shop>> map = new TreeMap<Integer,List<Shop>>();
			
			for(ShopType stype : shopTypeList){
				int id = stype.getInt("id");
				List<Shop> sList = Shop.dao.find(" select * from shop p where type = ? ",id);
				map.put(id, sList);
			}
			
			setAttr("shopTypeList", shopTypeList);
			setAttr("map",map);
			
			render("/template/app/shopList.html");
			return;
		}
		
		
		
		List<ProductType> list = ProductType.dao.find("select * from product_type where pid>0 and shop_id= ? order by seq ;",shopId);

		Map<Integer,List<Record>> map = new TreeMap<Integer,List<Record>>();
		
		for(ProductType ptype : list){
			int id = ptype.getInt("id");
			List<Record> pList = Db.find(" select id,p.name,now_price,logo,p.desc from product p where product_type_id = ? order by seq ",id);
			map.put(id, pList);
		}
		
		setAttr("productTypeList", list);
		setAttr("map",map);
		
		render("/template/app/productList.html");
	}
	
	/*
	 * 代客下单加入购物篮
	 */
	public void toCart(){
		
		String mobileNo = getPara("mobileNo");
		
		Integer shopId= getParaToInt("id");
		if(shopId==null) shopId=1;
		
		String cartCookieProId = "";//取出放在cookie中的商品id
		
		List<Product> list = new ArrayList<Product>();		
		
		try{
			String cookie = getCookie("shopMer_"+String.valueOf(shopId));
			if(StringKit.notBlank(cookie)){
				cartCookieProId = URLDecoder.decode(cookie, "UTF-8");
				if(cartCookieProId != null){
					String[] proIds = cartCookieProId.split(",");
					for(String id : proIds){
						Product proPo = Product.dao.findById(Integer.valueOf(id));
						list.add(proPo);
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		Collections.sort(list, new Comparator<Product>() {
            public int compare(Product pro0, Product pro1) {
                Integer seq0 = pro0.getInt("seq")==null ? 0 : pro0.getInt("seq");
                Integer seq1 = pro1.getInt("seq")==null ? 0 : pro1.getInt("seq");
            	return seq0.compareTo(seq1);
            }
        });
		
		Customer customer = Customer.dao.getCustomerByName(mobileNo);
		if(customer != null){
			setAttr("frontSign",customer.getInt("front_sign"));
		}
		
		setAttr("shopPo", Shop.dao.findById(shopId));
		setAttr("productList", list);
		setAttr("mobileNo",mobileNo);
		
		render("/template/app/cart.html");
	}
		
	/*
	 * 下单后，发送短信通知用户
	 */
	public void sendSms(){
		
//		int shopId = getParaToInt("shop_id");
		
		Shop shop = getSessionAttr(Content.SESSION_SHOP);
		int shopId = shop.getInt("id");
		
		int frontSign = getParaToInt("frontSign");//是否需要定金标记
		
		String sumArrayArea = getAttr("sumArrayArea"); //先从attr里面取 如果没有就从页面参数取
		if(sumArrayArea==null) sumArrayArea=getPara("sumArrayArea");
		
		String mobileNo = getAttr("mobileNo"); //先从attr里面取 如果没有就从页面参数取
		if(mobileNo==null) mobileNo=getPara("mobileNo");
		
		Date date = new Date();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			TempCart tempCart = new TempCart();
			tempCart.set("shop_id", shopId);
			tempCart.set("phone", mobileNo);
			tempCart.set("cart_content", sumArrayArea);
			tempCart.set("sign", 0);
			tempCart.set("front_sign", frontSign);
			tempCart.set("create_time", date);
			tempCart.set("update_time", date);

			tempCart.save();
			
			String longUrl = "http://hyt.smpay.cn/app/toOrder/"+tempCart.getInt("id");
			TempCart t = TempCart.dao.findById(tempCart.getInt("id"));
			log.info(tempCart.getInt("id")+"-----11---------->"+t.getInt("sign"));
//			String longUrl = "http://localhost:8080/app/toOrder/"+tempCart.getInt("id");
			String shortUrl = Tools.shortUrlBySina(longUrl);
			if(shortUrl.contains("3p") || shortUrl.contains("3P")){
				shortUrl = Tools.shortUrlBySina(longUrl);
			}
			System.out.println(shortUrl);
			log.info("------shortUrl------>"+shortUrl);

			String urlString = "http://220.181.190.42/sendMultiSmsIface";

			String usrname = "ykttest";//短信账户名
			String mdrSalt = "8cd94f156c8c4f8483d74bb4";//加密盐
			String content = "";//短信内容
			String qianmin = "一卡通";//签名
			String phone = mobileNo;//手机号码串
			
			StringBuffer sb = new StringBuffer("");
			sb.append("您购买的商品已下单成功，请点击  ").append(shortUrl).append(" 确认订单，谢谢！");
			if(shopId == 5){
				qianmin = "e食通";//签名
				//HI~您的订单已成功下达，请点击{0-自动生成网址订单编号}确认订单并尽快支付。E食通，您的生活小秘书！
				sb = new StringBuffer("");
				sb.append("HI~您的订单已成功下达，请点击 ").append(shortUrl).append(" 确认订单并尽快支付。e食通，您的生活小秘书！");
			}
			
			content = sb.toString();

			String requestContent = Tools.getSmsContent(usrname, mdrSalt, content, qianmin, phone);
			Tools.request(urlString, requestContent);//发送短信
			
			map.put("Msg", "Ok");
		} catch (Exception e) {
			map.put("Msg", "发送失败，请重新操作");
			e.printStackTrace();
		} 
		renderJson(map);
	}
	
	/*
	 * 用户收到短信后，点击短信中的链接，转向订单确认页
	 */
	public void toOrder(){
		log.info("----toOrder----");
		String ip = getIpAddr();
		log.info("-ip--------->"+ip);
		int id = getParaToInt();
		if(ip.contains("180.149.135.")){
			renderJson("");
			return;
		}
		log.info("-----转向订单确认页--------");
		TempCart tc = TempCart.dao.findById(id);
		int sign = tc.getInt("sign");
		if(sign == 1){
			String text="订单已失效！";
			renderText(text, "text/html");
			return;
		}
		
		String params = tc.getStr("cart_content"); 
		String phone = tc.getStr("phone");
		int shopId = tc.getInt("shop_id");
		int frontSign = tc.getInt("front_sign");
		
		Shop shop = Shop.dao.findById(shopId);
		
		Customer customer = Customer.dao.getCustomerByName(phone);
		if(customer == null ){
			customer = new Customer();
			Date time = new Date();
			customer.set("username", phone);
			customer.set("password", "123456");
			customer.set("phone", phone);
			customer.set("customer_no",time.getTime());
			customer.set("create_time",time);
			customer.set("join_time", time);
			customer.set("shop_id", shopId);
			customer.set("front_sign", frontSign);
			customer.save();
		}
		setSessionAttr(Content.SESSION_LOGIN_USER, customer);
		
		setSessionAttr(Content.SESSION_SHOP, shop);
		
		//7,2|6,1
		List<Object> list = new ArrayList<Object>();
		float subTotal = 0.0f;
		if(StringKit.notBlank(params)){
			String[] paramArray = params.split("\\|");
			for(String temp : paramArray){
				if(StringKit.notBlank(temp)){
					String[] tempArray = temp.split(",");
					Map<String,Object> map = new HashMap<String,Object>();
					Product proPo = Product.dao.findById(Integer.valueOf(tempArray[0]));
					float total = proPo.getBigDecimal("now_price").floatValue()*Integer.valueOf(tempArray[1]);
					map.put("proPo", proPo);
					map.put("product_num", tempArray[1]);
					map.put("product_total", total);
					list.add(map);
					subTotal += total;
				}
			}
		}
		
		//tc.set("sign", 1);
		//tc.update();
		
		setAttr("addrList",CustomerAddress.dao.findByCustomerId(customer.getInt("id")));
		setAttr("postageList",Postage.dao.findPostageByShopId(shopId));
		setAttr("shopPo", shop);
		setAttr("productList", list);
		setAttr("subTotal", subTotal);
		
		setAttr("frontSign", frontSign);

		setAttr("productParams", params);

		TokenManager.createToken(this, tokenName, tokenTout);
		setAttr(tokenName, getSessionAttr(tokenName));
		
		render("/template/submitOrders/view.html");

	}
	
	public String getIpAddr() {
		//HttpServletRequest request = ServletActionContext.getRequest();
		String ip = getRequest().getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRequest().getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRequest().getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRequest().getRemoteAddr();
		}
		return ip;
	}
	
	public static void main(String[] args) {
		String usrname = "ykttest";//账户名
		String mdrSalt = "8cd94f156c8c4f8483d74bb4";//加密盐
		String content = "测试短信内容";//短信内容
		String sign = "一卡通";//签名
		String phone = "18926066293";//手机号码串
		
		String urlString = "http://manage.smpay.cn/sendMultiSmsIface";
		String requestContent = Tools.getSmsContent(usrname, mdrSalt, content, sign, phone);
		
		try {
			Tools.request(urlString, requestContent);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}
